import {uShareMyDev} from './../../../api/setting'

import {observable, computed, action} from 'mobx'
import {createContext} from 'react'
import ChildrenPageUtils from '@/store/extends'
import {uSelectMyShareData} from '@/api/setting'
import {getStorage} from '@/utils/localstoreage'
import Taro from '@tarojs/taro'
import {CommonEventFunction, FormProps} from '@tarojs/components'

class Sharedev extends ChildrenPageUtils {
  @observable detailData: Setting.MyShareData = {
    shareCount: 0,
    shareLinkDevCount: 0,
    passiveShareCount: 0
  }
  @action.bound
  async updateDetailData(notShowLoading?: boolean) {
    let userId = getStorage('userId')
    if (!userId) return

    if (!notShowLoading)
      Taro.showLoading({
        title: '加载中...'
      })

    if (!this.pageQuery.devId) {
      Taro.showToast({
        icon: 'none',
        title: '请重新进入'
      })
      Taro.navigateBack()
      return
    }

    let res = await uSelectMyShareData({devId: this.pageQuery.devId, userId})
    if (res && res.result === 'success') {
      this.detailData = res.data
    } else {
      this.detailData = {
        shareCount: 0,
        shareLinkDevCount: 0,
        passiveShareCount: 0
      }
    }
    if (!notShowLoading) Taro.hideLoading()
  }

  @observable errorMsg: string = ''
  @computed get canShowErrorMsg() {
    return (this.errorMsg ?? '') !== ''
  }
  @action.bound
  setErrorMsg(data: string) {
    this.errorMsg = data
  }
  @action.bound
  shareDev(phone: string) {
    if (!phone) {
      Taro.showToast({
        icon: 'error',
        title: '请输入手机号'
      })
      return
    }
    if (!this.pageQuery.devId) {
      Taro.showToast({
        icon: 'none',
        title: '请重新进入'
      })
      Taro.navigateBack()
      return
    }
    uShareMyDev({
      shareUserPhone: phone,
      devId: this.pageQuery.devId
    })
      .then(res => {
        this.errorMsg = ''
        Taro.showToast({
          icon: 'success',
          title: '分享成功'
        })
        this.updateDetailData(true)
      })
      .catch(err => {
        if (err && err.result === 'error' && err.msg) {
          this.errorMsg = err.msg
          Taro.showModal({
            title: '提示',
            content: err.msg
          })
          this.updateDetailData(true)
        }
      })
  }
}
export const shareDevStore = createContext(new Sharedev())
